<template>
    <view class="content">
        <view class="head">
            <view class="head-l">{{ infoData.shopName }}</view>
            <!-- <view class="head-r">距离{{infoData.discount}}m</view> -->
        </view>
        <view class="main">
            <view class="box">
                <view class="idle" v-if="onLineStore.length">
                    <view class="tit">{{ optionsNo ? "当前扫码球台" : "当前空闲球台" }}</view>
                    <view class="list">
                        <view class="item" v-for="item in onLineStore" @click="onCheck(item)" :key="item.id">
                            <view class="item-t">
                                <view class="type">中式八球</view>
                                <image class="isckeck" v-show="item.id != checkStore.id" src="/static/jt-no.png"></image>
                                <image class="isckeck" v-show="item.id == checkStore.id" src="/static/jt-check.png"></image>
                            </view>
                            <view class="name">{{ item.billiardName }}</view>
                            <!-- <view class="time">可用时长：{{filterHours(item.leisureTime || 0)}}</view> -->
                        </view>
                    </view>
                </view>
                <view class="useing" v-if="offLineStore.length > 0 && Object.keys(checkStore).length == 0">
                    <view class="tit">
                        <view class="tit-l">
                            <text>使用中球台</text>
                            <!-- <image src="/static/help.png" /> -->
                        </view>
                        <!-- <view class="tit-r">
              <view>提前预订</view>
              <image src="/static/jt-blue.png" />
            </view> -->
                    </view>
                    <view class="list">
                        <view class="item" v-for="item in offLineStore">
                            <view class="item-t">
                                <view class="type">中式八球</view>
                            </view>
                            <view class="name">{{ item.billiardName }}</view>
                            <view class="time">
                                释放剩余:
                                <uni-countdown color="#999" :font-size="10" splitorColor="#999" :show-day="false" :hour="item.lastHours" :minute="item.lastMinute" :second="item.lastSecond"></uni-countdown>
                            </view>
                        </view>
                    </view>
                </view>
                
				
				<view class="useing" v-if="closeBilliard.length > 0">
				        <view class="tit">
				            <view class="tit-l">
				                <text>维修中球台</text>
				            </view>
				        </view>
				        <view class="list">
				            <view class="item" v-for="item in closeBilliard">
				                <view class="item-t">
				                    <view class="type">中式八球</view>
				                </view>
				                <view class="name">{{ item.billiardName }}</view>
				                <view class="time">
				                    维修中
				                </view>
				            </view>
				        </view>
				    </view>
				
				
				<view class="select-tq" v-if="Object.keys(checkStore).length > 0">
                    <view class="tit">
                        <view class="tit-l">
                            <view>已选球台</view>
                            <view class="name">{{ checkStore.billiardName }}</view>
                        </view>
                        <view class="tit-r" v-if="beginAenEndTime">{{ beginAenEndTime }} {{ selectHourStr }}</view>
                        <viwe class="tit-r" v-else>点击选择结束时间或开台时长</viwe>
                    </view>
                    <view class="center">
                        <view v-for="(item, index) in fourTimes" :class="{ last: index === 4 }" :key="index">
                            <view class="item-list">
                                <view class="label" :key="item.value">{{ item.label }}</view>
                                <view class="item-child-list">
                                    <view class="item-child" @click="selectTime(item, itemc)" :class="{ check: itemc.check, desabled: groupCouponId }" v-for="(itemc, index) in item.list" :key="index"></view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="times">
                        <view @click="selectHours(item.value, item.label)" :class="{ check: item.value === selectHour }" v-for="item in slelctTimes" class="item" :key="item.value">{{ item.label }}</view>
                    </view>
                </view>
                <view class="total-price" v-show="Object.keys(checkStore).length > 0">
                    <view class="price-tit">
                        <view>总价</view>
                        <view>{{ payPriceObj.totalPrice / 100 }}元</view>
                    </view>
                    <view class="times">
                        <view class="item" v-for="item in payPriceObj.itemGroupList" :key="item.skuId">
                            <!-- <view>{{ beginAenEndTime }}</view> -->
                            <view style="flex: 1">{{ item.orderItemStartTime }}--{{ item.orderItemEndTime }}</view>
                            <view style="flex: 1">{{ ((item.price * 2) / 100).toFixed(0) }} 元/小时</view>
                            <view style="width: 120rpx; text-align: right">{{ (item.subItemPrice / 100).toFixed(2) }}元</view>
                        </view>
                        <!-- <view class="discount" style="text-align:right" v-if="payPriceObj.totalPrice !== payPriceObj.payPrice">-{{((payPriceObj.totalPrice - payPriceObj.payPrice) / 100).toFixed(2)}}元</view> -->
                    </view>
                    <view class="coupon" @click="goCoupon" v-if="!groupCouponId && Object.keys(checkStore).length > 0 && payPriceObj.items.length">
                        <view style="flex: 1">优惠券</view>
                        <view class="coupon-r">
                            <view class="coupon-num" v-if="!groupBuyCouponId">{{ couponNum || 0 }}张可用</view>
                            <view class="coupon-num" v-else>-{{ ((payPriceObj.totalPrice - payPriceObj.payPrice) / 100).toFixed(2) }}元</view>
                            <image class="jt" src="/static/jt.png" />
                        </view>
                    </view>
                    <view class="group-coupon" v-if="groupCouponId">
                        <view class="coupon-name">{{ groupCouponObj.name }}</view>
                        <view class="coupon-num" v-if="payPriceObj.totalPrice">-{{ payPriceObj.totalPrice / 100 }}元</view>
                    </view>
                    <view class="preferential-rules">
                        <view class="name">优惠规则</view>
                        <view class="p-rules-r">
                            <view>
                                已优惠
                                <text class="p-rules-r-l">¥{{ ((payPriceObj.totalPrice - payPriceObj.payPrice) / 100).toFixed(2) }}</text>
                            </view>
                            <view>
                                小计
                                <text class="p-rules-r-r">¥{{ payPriceObj.payPrice / 100 }}</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="group-qudao box" @click="goCouponDetail" v-if="!groupCouponId && optionsNo">
                <view class="qudao">
                    <image src="/static/dy.png"></image>
                    <image src="/static/mt.png"></image>
                    <image src="/static/dzdp.png"></image>
                    <view class="text">团购券开台</view>
                </view>
                <image class="jiantou" src="/static/jt.png" />
            </view>
            <view class="box pay-type" v-show="payPriceObj.items.length && !groupCouponId">
                <view class="tit">支付方式</view>
                <view class="type-list">
                    <view class="item" v-for="(item, index) in payType" :key="index" @click="selectPayType(item)">
                        <view class="item-l">
                            <image class="icon" :src="item.icon" />
                            <view>
                                <view>
                                    {{ item.label }}
                                    <text v-if="item.value === 1">(¥{{ myWallet.balance / 100 }})</text>
                                </view>
                                <view @click.stop="goRecharge" v-if="noMoney && item.value === 1" class="desc">
                                    <text>余额不足，充值享优惠</text>
                                    <image class="jiantou" src="/static/jt.png" />
                                </view>
                            </view>
                        </view>
                        <!-- 钱包有钱 -->
                        <view class="item-r" v-if="!noMoney">
                            <!-- 钱包有钱但是优惠卷不支持钱包支付 -->
                            <view v-if="groupBuyCoupon?.payWay?.includes('wx_lite')">
                                <image src="/static/select-disabled.png" v-if="item.value === 1" />
                                <image src="/static/yhj-check.png" v-if="item.value === 2" />
                            </view>
                            <!-- 钱包有钱但是优惠卷只支持钱包支付 -->
                            <view v-else-if="groupBuyCoupon?.payWay?.includes('wallet')">
                                <image src="/static/select-disabled.png" v-if="item.value === 2" />
                                <image src="/static/yhj-check.png" v-if="item.value === 1" />
                            </view>
                            <view v-else>
                                <image src="/static/yhj-nocheck.png" v-if="payTypeCheck.value !== item.value" />
                                <image src="/static/yhj-check.png" v-if="payTypeCheck.value === item.value" />
                            </view>
                        </view>
                        <!--<view class="item-r" v-if="!noMoney">
              <image
                src="/static/yhj-nocheck.png"
                v-if="payTypeCheck.value !== item.value"
              />
              <image
                src="/static/yhj-check.png"
                v-if="payTypeCheck.value === item.value"
              />
            </view> -->
                        <!-- 钱包钱不够 -->
                        <view class="item-r" v-if="noMoney">
                            <!-- 钱包钱不够，但是只能钱包支付 -->
                            <view v-if="groupBuyCoupon?.payWay?.includes('wallet')">
                                <image src="/static/select-disabled.png" />
                            </view>
                            <view v-else>
                                <image src="/static/yhj-check.png" v-if="item.value === 2" />
                                <image src="/static/select-disabled.png" v-if="noMoney && item.value === 1" />
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- || (groupBuyCoupon?.payWay?.includes('wx_lite')) -->
        <view class="footer" @click="submit" v-if="!(noMoney && groupBuyCoupon?.payWay?.includes('wallet'))">
            <view class="btn">
                <view class="btn-l">
                    <view class="tatol-price">¥{{ payPriceObj.payPrice / 100 }}</view>
                    <view class="discount" v-if="payPriceObj.totalPrice !== payPriceObj.payPrice">已优惠：¥{{ ((payPriceObj.totalPrice - payPriceObj.payPrice) / 100).toFixed(2) }}</view>
                </view>
                <view class="btn-r">
                    <view v-if="onLineStore.length">{{ groupCouponId ? "团购券支付" : payTypeCheck.label }}</view>
                    <view v-if="!onLineStore.length">球桌正在使用</view>
                    <image class="jt" src="/static/jt-b.png" />
                </view>
            </view>
        </view>
        <uni-popup ref="activePopup">
            <view class="active-popup-box">
                <view class="active-top">
                    <image class="active-top-img" :src="topUrl" mode="scaleToFill" />
                    <view class="title">{{ activeObj.name }}</view>
                </view>
                <image class="close" src="../../static/close.png" @click="activeClose" />
                <view class="active-popup" :style="{ backgroundImage: `url('${activeBackGround}')` }">
                    <!-- <view class="title">{{ activeObj.name }}</view> -->
                    <view class="list">
                        <view class="item box" v-for="item in activeList" :style="filterBgImg(item)" :key="item.id">
                            <view class="item-l">
                                <!-- <view class="time">{{ discountTypeObj[item.discountType] || "" }}</view> -->
                                <view class="time" v-if="item.discountType == 11">{{ item.discountPrice / 100 }}元</view>
                                <view class="time-m" v-if="item.discountType == 11">满{{ item.usePrice / 100 }}元</view>
                                <view class="time" v-if="item.discountType == 12">{{ item?.discountTime }}折</view>
                                <view class="time-m" v-if="item.discountType == 12">满{{ item?.discountLimitTime }}小时</view>
                            </view>
                            <view class="item-r">
                                <view class="name">{{ item.name }}</view>
                                <view class="time" v-if="item.validityType == 1">有效期至{{ filterTime(item.validEndTime) }}</view>
                                <view class="time" v-if="item.validityType == 2">有效期至{{ filterTimeToDay(item.fixedEndTerm - item.fixedStartTerm + 1) }}</view>
                            </view>
                        </view>
                    </view>
                    <!-- <view class="btn" @click="activeClose">立即领取</view> -->
                </view>
            </view>
        </uni-popup>
    </view>
</template>
<script setup>
import { ref, reactive, watch, getCurrentInstance, onMounted } from "vue";
import { getConfirmView, createBilliardOrder, orderSubmit, billiardSettlement, listGroupBuy, getWallet, getcoupon, getUnusedCount, getBilliardMatchCouponList, getListActivity } from "@/service/index";
import { onLoad, onShow, onReady } from "@dcloudio/uni-app";
import { filterHours } from "@/untils/common";
import dayjs from "dayjs";
import _ from "lodash";
const infoData = ref({});
const groupBuyCouponId = ref(null); // 优惠卷
const groupCouponId = ref(null); // 团购卷
const groupCouponObj = ref({}); // 团购卷
const groupBuyCoupon = ref({});
const setectTimeObj = ref({
    beginTime: null,
    endTime: null,
});
const checkStore = ref({});
const optionsNo = ref(null); // 扫码进入带桌号
const fourTimes = ref([]);
const selectHour = ref(null);
const selectHourStr = ref("");
const beginAenEndTime = ref("");
const onLineStore = ref([]); // 在线桌子
const offLineStore = ref([]); // 离线桌子
const shopId = ref(null);
const payTypeCheck = ref({});
const noMoney = ref(false); // 钱包余额不足
const myWallet = ref({ balance: 0 });
const orderDuration = ref(""); // 开台小时数
const closeBilliard = ref([]);
const payType = ref([
    {
        value: 1,
        label: "余额支付",
        icon: "/static/wx-pay-2.png",
    },
    {
        value: 2,
        label: "微信支付",
        icon: "/static/wx-pay-1.png",
    },
]);
const payPriceObj = ref({
    payPrice: 0,
    totalPrice: 0,
    items: [],
    itemGroupList: [],
});
const slelctTimes = [
    {
        value: -0.5,
        label: "30分钟",
    },
    {
        value: 0,
        label: "1小时",
    },
    {
        value: 1,
        label: "2小时",
    },
    {
        value: 2,
        label: "3小时",
    },
    {
        value: 3,
        label: "4小时",
    },
];
const selectPayType = item => {
    if (noMoney.value) {
        return;
    }
    if (groupBuyCoupon.value?.payWay?.includes("wx_lite")) {
        return;
    }
    if (groupBuyCoupon.value?.payWay?.includes("wallet")) {
        return;
    }
    payTypeCheck.value = item;
};
const filterTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}
const filterTimeToDay = (date) => {
  return dayjs().add(date, 'day').format('YYYY-MM-DD HH:mm:ss')
}
const filterBgImg = item => {
    const obj = activeObj.value.itemList.filter(v => {
        return v.templateId === item.id;
    })?.[0];
    if (obj) {
        return {
            backgroundImage: `url('${obj.itemBackgroundUrl}')`,
            backgroundPosition: "center center",
            backgroundRepeat: "no-repeat",
            backgroundSize: "cover",
        };
    }
};
const activeClose = () => {
    activePopup.value.close();
    uni.showToast({
        title: "领取成功，请前往我的优惠券查看",
        icon: "none",
    });
};
const getMyWallet = async () => {
    await getWallet({ isLogin: false }).then(res => {
        console.log(res, "res");
        myWallet.value = res;
    });
};
const goRecharge = () => {
    uni.navigateTo({
        url: "/pages/recharge/index",
    });
};
const createTimeIntervals = () => {
    const now = new Date();
    const result = [];
    let nextHourTime;

    // 如果当前时间的分钟数不为0，则计算下一个整点时间
    if (now.getMinutes() !== 0 || now.getSeconds() !== 0 || now.getMilliseconds() !== 0) {
        nextHourTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 0, 0, 0);
    }
    // 否则当前时间已经是整点，那么下一个整点就是下一小时
    else {
        nextHourTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 0, 0, 0);
    }
    result.push({
        time: dayjs().format("HH:mm"),
        label: "",
        index: 0,
        list: [
            {
                time: dayjs(nextHourTime).format("HH:mm"),
                index: 0,
                stamp: dayjs(nextHourTime).format(),
            },
        ],
    });
    for (let i = 0; i <= 4; i++) {
        const hourLater = new Date(dayjs(nextHourTime) + i * 3600000); // 加上i小时
        const timeStr = hourLater.getHours() + ":" + (hourLater.getMinutes() < 10 ? "0" : "") + hourLater.getMinutes();
        const timeLabel = hourLater.getHours();
        const timeIndex = i;
        let list = [];
        for (let j = 1; j < 3; j++) {
            // 每个小时内分为3个20分钟的时间段
            const twentyMinutesLater = new Date(hourLater.getTime() + j * 1800000); // 加上j个20分钟
            const twentyMinStr = twentyMinutesLater.getHours() + ":" + (twentyMinutesLater.getMinutes() < 10 ? "0" : "") + twentyMinutesLater.getMinutes();
            list.push({ time: twentyMinStr, index: j, stamp: twentyMinutesLater });
        }
        if (i === 4) {
            list = [];
        }
        result.push({
            time: timeStr,
            label: timeLabel + ":00",
            index: timeIndex,
            list: list,
        });
    }
    console.log(result);
    return result;
};
const removeTrailingZerosInFraction = num => {
    num = String(num);
    var parts = num.split(".");
    console.log(parts);
    if (parts.length === 1) return num; // 没有小数部分
    if (parts[1] == 0) {
        return parts[0];
    } else {
        return num;
    }
};
const selectTime = async (item, citem) => {
    if (groupCouponId.value) return; // 使用团购卷时，不能修改
    console.log(item.label);
    selectHour.value = null;
    fourTimes.value.forEach(v => {
        if (v.index < item.index) {
            v.list.forEach(v2 => {
                v2.check = true;
            });
        } else {
            v.list.forEach(v2 => {
                v2.check = false;
            });
        }
        if (v.index === item.index) {
            v.list.forEach(v2 => {
                console.log(citem.index, v2.index, citem.index >= v2.index);
                if (citem.index >= v2.index) {
                    v2.check = true;
                }
            });
        }
    });
    beginAenEndTime.value = fourTimes.value[0].time + "-" + citem.time;
    setectTimeObj.value = {
        beginTime: fourTimes.value[0].time,
        endTime: citem.stamp,
    };
    const date1 = new Date(`${dayjs().format("YYYY-MM-DD")} ${setectTimeObj.value.beginTime}:00`);
    // const date2 = new Date(`${dayjs().format('YYYY-MM-DD')} ${setectTimeObj.value.endTime}:00`);
    const date2 = dayjs(setectTimeObj.value.endTime).valueOf();
    console.log(date2, "date2", dayjs(setectTimeObj.value.endTime).valueOf());
    const diffTime = Math.abs(date2 - date1);
    const diffDays = diffTime / (1000 * 60 * 60) > 1 ? (diffTime / (1000 * 60 * 60)).toFixed(1) : diffTime / (1000 * 60);
    console.log(removeTrailingZerosInFraction(diffDays), "----");
    orderDuration.value = (diffTime / (1000 * 60 * 60)).toFixed(2);
    console.log(orderDuration.value, "orderDuration.value");
    selectHourStr.value = removeTrailingZerosInFraction(diffDays) + (diffTime / (1000 * 60 * 60) > 1 ? "小时" : "分钟");
    console.log(diffDays);
    if (groupBuyCouponId.value) {
        uni.showToast({
            title: "当前下单时长发生改变，请重新选择优惠券",
            icon: "none",
            duration: 2000,
        });
        // uni.showModal({
        //     title: '当前下单时长发生改变，请重新选择优惠券',
        //     showCancel: false,
        //   });
        groupBuyCouponId.value = null;
        groupBuyCoupon.value = {};
        uni.removeStorageSync("couponData");
        await sleep(1000);
    }
    getPayMount();
};
const selectHours = async (value, label, type = true) => {
    if (groupCouponId.value && type) {
        // 使用团购卷的时候不能点击修改
        return;
    }
    if (groupBuyCouponId.value) {
        uni.showToast({
            title: "当前下单时长发生改变，请重新选择优惠券",
            icon: "none",
            duration: 2000,
        });

        // uni.showModal({
        //     title: '当前下单时长发生改变，请重新选择优惠券',
        //     showCancel: false,
        //   });
        groupBuyCouponId.value = null;
        groupBuyCoupon.value = {};
        uni.removeStorageSync("couponData");
        await sleep(1000);
    }
    setTimes();
    selectHour.value = value;
    selectHourStr.value = label;
    orderDuration.value = value + 1;
    const endtime = dayjs()
        .add(selectHour.value + 1, "hour")
        .format("YYYY-MM-DD HH:mm:ss");
    fourTimes.value.forEach((v, index) => {
        console.log(value, index);
        v.list.forEach(v2 => {
            console.log(dayjs(v2.stamp).valueOf() - dayjs(endtime).valueOf());
            if (dayjs(v2.stamp).valueOf() - dayjs(endtime).valueOf() < 1800000) {
                v2.check = true;
            } else {
                v2.check = false;
            }
        });
        // if (index <= value) {
        //   v.list.forEach((v2) => {
        //     v2.check = true;
        //   });
        // } else {
        //   v.list.forEach((v2) => {
        //     v2.check = false;
        //   });
        // }
    });
    // beginAenEndTime.value = fourTimes.value[0].time + "-" + fourTimes.value[value + 1].time;
    beginAenEndTime.value =
        fourTimes.value[0].time +
        "-" +
        dayjs()
            .add(selectHour.value + 1, "hour")
            .format("HH:mm");
    setectTimeObj.value = {
        beginTime: fourTimes.value[0].time,
        endTime: endtime,
    };
    console.log(setectTimeObj.value, "setectTimeObj.value");
    if (groupCouponId.value && optionsNo.value) {
        getPayMount();
    }
    if (type) {
        getPayMount();
    }
};
const setTimes = () => {
    fourTimes.value = createTimeIntervals();
    console.log(fourTimes.value);
};
const sleep = ms => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, ms);
    });
};
const getData = async () => {
    uni.showLoading({
        mask: true,
    });
    onLineStore.value = [];
    offLineStore.value = [];
	closeBilliard.value=[];
    await getConfirmView({ shopId: shopId.value }).then(res => {
        uni.hideLoading();
        infoData.value = res || [];
        infoData.value.billiardMainList?.forEach(v => {
			if(v.open === 2){
				//v.open === 2 说明已经关台（已经维修中），其他不等于2的内容，认为是营业中的。
				//只有营业中的球台，才再区分上下线（开台、关台）
				closeBilliard.value.push(v);
			}else{
				if (v.online === 2) {
				    onLineStore.value.push(v);
				}
				if (v.online === 1) {
				    // 处理占用时间
				    // if (v.leisureTime > 60) { // 大于60s
				    //   if(v.leisureTime > 3600){
				    //     v.lastHours = Math.floor(v.leisureTime / 3600);
				    //     v.lastMinute = v.leisureTime % 3600;
				    //   } else {
				    //     v.lastMinute = Math.floor(v.leisureTime / 60);
				    //   }
				    // } else {
				    //   // v.lastMinute = v.leisureTime;
				    //   v.lastSecond = v.leisureTime;
				    // }
				    v.lastHours = Math.floor(v.leisureTime / 3600);
				    v.lastMinute = Math.floor((v.leisureTime % 3600) / 60);
				    v.lastSecond = v.leisureTime % 60;
				    offLineStore.value.push(v);
				}
			}
        });
        console.log(offLineStore.value);
        offLineStore.value = _.uniqBy(offLineStore.value, "billiardNo");
        if (optionsNo.value) {
            console.log("---1--");
            let arr = onLineStore.value.filter(v => {
                return v.billiardNo == optionsNo.value;
            });
            console.log(arr, "arr");
            if (arr && arr.length) {
                arr = _.uniqBy(arr, "billiardNo");
                onLineStore.value = arr;
                onCheck(arr[0]);
            } else {
                onLineStore.value = [];
            }
        }
    });
};
const getListGroupBuy = () => {
    uni.showLoading({
        mask: true,
    });
    listGroupBuy({}).then(res => {
        uni.hideLoading();
        console.log(res, "res");
        infoData.value.groupBuyList = res || [];
        if (groupCouponId.value) {
            groupCouponObj.value = infoData.value.groupBuyList.filter(v => {
                console.log(v.id, groupCouponId.value);
                return v.id == groupCouponId.value;
            })[0];
            console.log(groupCouponObj.value.name, "-----");
            selectHours(groupCouponObj.value.billiardUseRuleVO.useTimeLimit - 1, `${groupCouponObj.value.billiardUseRuleVO.useTimeLimit}小时`, false);
        }
    });
};
// 优惠卷
const goCoupon = () => {
    uni.navigateTo({
        url: `/pages/coupon/orderCoupon?no=${optionsNo.value}&id=${shopId.value}`,
    });
};
// 团购卷
const goCouponDetail = () => {
    uni.navigateTo({
        url: `/pages/coupon/detail?no=${optionsNo.value}&id=${shopId.value}`,
    });
};
const couponNum = ref(0);
// 获取优惠卷列表 ----- 2024-6-10 废弃
const getcouponList = () => {
    getUnusedCount().then(res => {
        couponNum.value = res;
    });
};
// 新获取订单可用优惠卷数据
const getNewCouponList = data => {
    const params = {
        ...data,
    };
    getBilliardMatchCouponList(params).then(res => {
        couponNum.value = res?.filter(v => v.matchFlag === 1).length || 0;
        uni.setStorageSync("orderUserCouponList", res);
    });
};
const submit = () => {
    if (!checkStore.value.id) {
        uni.showToast({
            title: "请先选择台球桌",
            icon: "none",
        });
        return;
    }
    if (!payPriceObj.value.items.length) {
        uni.showToast({
            title: "请选择时间",
            icon: "none",
        });
        return;
    }
    // 选择的时间必须大于三十分钟
    if (dayjs(setectTimeObj.value.endTime).valueOf() - dayjs(`${dayjs().format("YYYY-MM-DD")} ${setectTimeObj.value.beginTime}:00`).valueOf() < 1800000) {
        uni.showToast({
            title: "开台时长至少需达到30分钟",
            icon: "none",
        });
        return;
    }
    if (groupCouponId.value) {
        uni.showModal({
            content: "是否确认核销团购券并开台？",
            success: res => {
                if (res.confirm) {
                    creatSubmit();
                } else if (res.cancel) {
                }
            },
        });
    } else if (payTypeCheck.value.value == 1) {
        uni.showModal({
            content: "确认使用余额支付并立即开台？",
            success: res => {
                if (res.confirm) {
                    creatSubmit();
                } else if (res.cancel) {
                }
            },
        });
    } else {
        creatSubmit();
    }
};
const creatSubmit = () => {
    const params = {
        items: payPriceObj.value.items,
        couponId: groupBuyCouponId.value || groupCouponId.value,
        startTime: `${dayjs().format("YYYY-MM-DD")} ${setectTimeObj.value.beginTime}:00`,
        endTime: dayjs(setectTimeObj.value.endTime).format("YYYY-MM-DD HH:mm:00"),
        billiardMainId: checkStore.value.id,
        billiardMainName: checkStore.value.billiardName,
        remark: "",
        channelCode: "wx_lite",
        orderDuration: Math.abs(orderDuration.value),
    };
    if (payTypeCheck.value.value == 1) {
        params.channelCode = "wallet";
    }
    uni.showLoading({
        mask: true,
    });
    createBilliardOrder(params)
        .then(res => {
            payOrder(res);
        })
        .catch(() => {
            uni.hideLoading();
        });
};
const payOrder = param => {
    console.log(param, "param");
    const orderid = param.id;
    const params = {
        id: param.payOrderId,
        channelCode: "wx_lite",
        channelExtras: {
            openid: uni.getStorageSync("openid"),
        },
        orderDuration: Math.abs(orderDuration.value),
    };
    if (payTypeCheck.value.value == 1) {
        params.channelCode = "wallet";
    }
    orderSubmit(params)
        .then(res => {
            const payConfig = JSON.parse(res.displayContent);
            console.log(payConfig, "pay");
            if (payTypeCheck.value.value == 1) {
                uni.showToast({
                    title: "支付成功",
                    icon: "none",
                });
                uni.redirectTo({
                    url: `/pages/order/detail?id=${orderid}`,
                });
                return;
            }
            uni.requestPayment({
                provider: "wxpay",
                timeStamp: payConfig.timeStamp,
                nonceStr: payConfig.nonceStr,
                package: payConfig.packageValue,
                signType: payConfig.signType,
                paySign: payConfig.paySign,
                success: res => {
                    console.log(orderid, "orderid");
                    uni.redirectTo({
                        url: `/pages/order/detail?id=${orderid}`,
                    });
                    uni.hideLoading();
                },
                fail: err => {
                    uni.hideLoading();
                    if (err.errMsg === "requestPayment:fail cancel") {
                        uni.showToast({
                            title: "支付已取消",
                            icon: "none",
                        });
                    } else {
                        console.log(err, "err");
                    }
                },
            });
        })
        .catch(err => {
            if (err.code === 1007002002) {
                uni.redirectTo({
                    url: `/pages/order/detail?id=${orderid}`,
                });
            }
            uni.hideLoading();
        });
};
// 选择桌号
const onCheck = item => {
    checkStore.value = item;
    console.log(setectTimeObj.value);
    if (setectTimeObj.value.endTime) {
        getPayMount();
    }
};
// 获取结算数据
const getPayMount = () => {
    const params = {
        billiardMainId: checkStore.value.id,
        startTime: `${dayjs().format("YYYY-MM-DD")} ${setectTimeObj.value.beginTime}:00`,
        endTime: dayjs(setectTimeObj.value.endTime).format("YYYY-MM-DD HH:mm:00"),
        couponId: groupBuyCouponId.value || groupCouponId.value,
        orderDuration: Math.abs(orderDuration.value),
    };
    if (params.endTime === "Invalid Date") {
        return;
    }
    uni.showLoading({
        mask: true,
    });

    billiardSettlement(params)
        .then(res => {
            uni.hideLoading();
            getNewCouponList({ ...params, items: res.items });
            payPriceObj.value.payPrice = res.price.payPrice;
            payPriceObj.value.totalPrice = res.price.totalPrice;
            payPriceObj.value.items = res.items;
            payPriceObj.value.itemGroupList = res.itemGroupList;
            if (!groupCouponId.value) {
                // 只能使用优惠卷支付
                if (groupBuyCoupon.value.payWay?.includes("wx_lite")) {
                    return;
                }
                if (payPriceObj.value.payPrice > myWallet.value.balance) {
                    payTypeCheck.value = payType.value[1];
                    noMoney.value = true;
                } else {
                    payTypeCheck.value = payType.value[0];
                    noMoney.value = false;
                }
            }
        })
        .catch(err => {
            uni.hideLoading();
            uni.showModal({
                title: err.msg || "请求数据出错",
                showCancel: false,
            });
        });
};
const activePopup = ref();
const activeList = ref([]);
const activeObj = ref({});
const topUrl = ref();
const activeBackGround = ref("");
// 领取活动劵
const getActive = (code) => {
    getListActivity({ eventCode: code }).then(res => {
        if (res.length) {
            activeObj.value = res[0];
            activeList.value = res[0].templateList;
            activeBackGround.value = res[0].backgroundUrl;
            topUrl.value = res[0].topUrl;
            activePopup.value.open();
        }
    });
};
const init = () => {
    infoData.value = {};
    fourTimes.value = [];
    checkStore.value = {};
    setectTimeObj.value = {
        beginTime: "",
        endTime: "",
    };
    onLineStore.value = [];
    offLineStore.value = [];
    selectHour.value = [];
    beginAenEndTime.value = "";
    selectHourStr.value = "";
    payPriceObj.value = {
        payPrice: 0,
        totalPrice: 0,
        items: [],
        itemGroupList: [],
    };
};
onLoad(options => {
    uni.removeStorageSync("couponData");
    shopId.value = options.id;
    if (options.no) {
        optionsNo.value = options.no;
        uni.setNavigationBarTitle({
            title: "扫码开台",
        });
       
    }
    if (options.couponId) {
        uni.setNavigationBarTitle({
            title: "团购券开台",
        });
        groupCouponId.value = options.couponId;
    }
    // getListGroupBuy();
});
const onShowInitFn = async () => {
    const couponData = uni.getStorageSync("couponData");
    console.log(couponData, "couponData");
    if (couponData) {
        // 选择了优惠卷
        groupBuyCoupon.value = couponData;
        groupBuyCouponId.value = couponData.id;
        if (groupBuyCoupon.value.payWay?.includes("wx_lite")) {
            payTypeCheck.value = payType.value[1];
        }
        getPayMount();
    } else if (checkStore.value.id) {
        console.log("选择过了");
        getPayMount();
    } else {
        init();
        await getData();
        //  getcouponList();
        await getMyWallet();
        setTimes();
        if (groupCouponId.value) {
            infoData.value.groupBuyList = uni.getStorageSync("couponList");
            groupCouponObj.value = infoData.value.groupBuyList.filter(v => {
                console.log(v.id, groupCouponId.value);
                return v.id == groupCouponId.value;
            })[0];
            console.log(groupCouponObj.value.name, "-----");
            selectHours(groupCouponObj.value.billiardUseRuleVO.useTimeLimit - 1, `${groupCouponObj.value.billiardUseRuleVO.useTimeLimit}小时`, false);
        }
    }
    getActive(11);
};
onShow(() => {
    uni.$on("login", function (data) {
        console.log("全局登陆事件");
        onShowInitFn();
        getActive(1);
    });
    onShowInitFn();
});
</script>
<style lang='less' scoped>
.content {
    display: flex;
    flex-direction: column;
    height: 100vh;

    // padding: 24rpx;
    .df-c {
        display: flex;
        align-items: center;
    }

    .head {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background-color: #fff;
        padding: 24rpx 26rpx;
        margin-bottom: 24rpx;

        .head-l {
            font-size: 28rpx;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            color: #333333;
        }

        .head-r {
            font-size: 26rpx;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            color: #0787f8;
        }
    }

    .main {
        background-color: #f7f7f7;
        padding: 24rpx;
        flex: 1;
        overflow-y: auto;
        .box {
            margin-bottom: 20rpx;
        }
        .idle,
        .useing {
            padding: 24rpx;

            .tit {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #000000;
                margin-bottom: 24rpx;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .tit-l {
                    display: flex;
                    align-items: center;

                    image {
                        width: 28rpx;
                        height: 28rpx;
                        margin-left: 12rpx;
                    }
                }

                .tit-r {
                    font-size: 24rpx;
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    color: #07b2f8;
                    display: flex;
                    align-items: center;
                    line-height: 34rpx;

                    image {
                        width: 14rpx;
                        height: 26rpx;
                        margin-left: 14rpx;
                    }
                }
            }

            .list {
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                justify-content: space-between;

                .item {
                    width: 308rpx;
                    height: 220rpx;
                    background: url("/static/qt-k.png") no-repeat;
                    background-size: contain;
                    position: relative;
                    margin-bottom: 20rpx;
                    box-sizing: border-box;
                    padding: 30rpx;

                    &:nth-child(2n-1) {
                        margin-right: 32rpx;
                    }

                    .item-t {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        margin-bottom: 22rpx;

                        .type {
                            width: 116rpx;
                            height: 36rpx;
                            line-height: 36rpx;
                            background: rgba(0, 0, 0, 0.2);
                            border-radius: 18rpx;
                            font-size: 22rpx;
                            font-family: PingFangSC, PingFang SC;
                            font-weight: 400;
                            color: #00eb7b;
                            text-align: center;
                        }
                        image {
                            width: 36rpx;
                            height: 36rpx;
                        }
                    }

                    .name {
                        font-size: 36rpx;
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 600;
                        color: #ffffff;
                        text-align: center;
                        margin-bottom: 10rpx;
                    }

                    .time {
                        font-size: 20rpx;
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 400;
                        color: #ffffff;
                        text-align: center;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }
                }
            }
        }

        .useing {
            .list {
                .item {
                    background: url("/static/qt-m.png") no-repeat;
                    background-size: contain;

                    .item-t {
                        .type {
                            background: rgba(0, 0, 0, 0.1);
                            color: #999999;
                        }
                    }

                    .name {
                        color: #999999;
                    }

                    .time {
                        color: #999999;
                    }
                }
            }
        }

        .select-tq {
            padding: 0 24rpx;

            .tit {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #000000;
                margin-bottom: 24rpx;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .tit-l {
                    display: flex;
                    align-items: center;

                    .name {
                        background: rgba(0, 154, 68, 0.2);
                        border-radius: 8rpx;
                        font-size: 28rpx;
                        font-weight: 400;
                        color: #009a44;
                        padding: 2rpx 10rpx;
                        margin-left: 16rpx;
                    }
                }

                .tit-r {
                    font-weight: 400;
                    color: #333333;
                }
            }

            .center {
                position: relative;
                display: flex;
                align-items: center;
                margin-bottom: 20rpx;
                justify-content: center;
                // .last {
                //   position: absolute;
                //   right: 0;
                //   top: 0;
                // }

                .item-list {
                    position: relative;
                    padding-top: 40rpx;
                    .label {
                        position: absolute;
                        color: #999999;
                        top: 0;
                        left: -40rpx;
                        font-size: 24rpx;
                    }

                    .item-child-list {
                        display: flex;
                        align-items: center;
                        min-height: 58rpx;

                        .item-child {
                            width: 58rpx;
                            height: 58rpx;
                            border: 1rpx solid #ddd;
                            border-radius: 10rpx;
                            margin-right: 10rpx;
                            &.desabled {
                                background-color: rgba(221, 221, 221, 1);
                            }
                            &.check {
                                background: #009a44;
                                border: 2rpx solid #009a44;
                                // box-shadow: inset -2rpx 0rpx 0rpx 0rpx #ffffff;
                            }
                        }
                    }
                }
            }

            .times {
                display: flex;
                align-items: center;
                flex-wrap: wrap;

                .item {
                    width: 108rpx;
                    height: 48rpx;
                    border-radius: 28rpx;
                    border: 2rpx solid #dddddd;
                    font-size: 28rpx;
                    color: #999999;
                    line-height: 48rpx;
                    margin-right: 16rpx;
                    margin-bottom: 10rpx;
                    text-align: center;
                    &.check {
                        color: #009a44;
                        border: 2rpx solid #009a44;
                    }
                }
            }
        }

        .total-price {
            padding: 30rpx 26rpx;
            border-bottom: 2rpx solid #eeeeee;

            .price-tit {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #000000;
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 10rpx;
            }

            .times {
                font-size: 26rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                color: #666666;
                margin-bottom: 20rpx;

                .item {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 10rpx;

                    &.check {
                        border: 2rpx solid #009a44;
                        color: #009a44;
                    }
                }
            }

            .coupon {
                font-size: 28rpx;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #000000;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .jt {
                    width: 18rpx;
                    height: 32rpx;
                    margin-left: 16rpx;
                }

                .coupon-r {
                    display: flex;
                    align-items: center;
                    margin-left: 10rpx;
                }

                .coupon-num {
                    color: #ff5d15;
                }
            }
            .group-coupon {
                background: rgba(255, 93, 21, 0.1);
                border-radius: 8rpx;
                height: 54rpx;
                line-height: 54rpx;
                font-size: 28rpx;
                color: #ff5d15;
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 0 10rpx;
                .coupon-name {
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    flex: 1;
                }
                .coupon-num {
                    white-space: nowrap;
                }
            }
            .preferential-rules {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: 20rpx;
                .name {
                    color: #ccc;
                    font-size: 24rpx;
                }
                .p-rules-r {
                    color: #000;
                    font-size: 26rpx;
                    display: flex;
                    align-items: center;
                    .p-rules-r-l {
                        color: #ff5d15;
                        margin-right: 20rpx;
                        margin-left: 10rpx;
                    }
                    .p-rules-r-r {
                        font-size: 32rpx;
                        font-weight: 600;
                        margin-left: 10rpx;
                    }
                }
            }
        }
        .group-qudao {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 20rpx 20rpx;
            background-color: #fff;
            .qudao {
                display: flex;
                align-items: center;
                justify-content: center;

                image {
                    width: 40rpx;
                    height: 40rpx;
                }
                .text {
                    margin-left: 10rpx;
                }
                image:nth-child(2) {
                    margin-right: 10rpx;
                    margin-left: 10rpx;
                }
            }
            .jiantou {
                width: 18rpx;
                height: 32rpx;
            }
        }
        .pay-type {
            padding: 20rpx 20rpx;
            background-color: #fff;
            .tit {
                font-weight: 600;
                font-size: 28rpx;
                color: #000000;
                margin-bottom: 22rpx;
            }
            .type-list {
                .item {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 32rpx;
                    .item-l,
                    .item-r {
                        display: flex;
                        align-items: center;
                        .desc {
                            display: flex;
                            align-items: center;
                            font-size: 24rpx;
                            color: #ff5d15;
                            .jiantou {
                                width: 12rpx;
                                height: 21rpx;
                                margin-left: 10rpx;
                            }
                        }
                    }
                    .item-r {
                        image {
                            width: 36rpx;
                            height: 36rpx;
                        }
                    }
                    .icon {
                        width: 72rpx;
                        height: 72rpx;
                        margin-right: 20rpx;
                    }
                }
            }
        }
    }

    .footer {
        padding: 34rpx 26rpx;
        box-shadow: 0rpx -12rpx 40rpx 0rpx rgba(0, 0, 0, 0.06);
        background-color: #fff;

        .btn {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            background: linear-gradient(315deg, #00b952 0%, #00e565 100%);
            border-radius: 60rpx;
            height: 120rpx;
            padding: 18rpx 42rpx;
            box-sizing: border-box;

            &::after {
                content: "";
                position: absolute;
                left: 60%;
                height: 100%;
                background-color: rgba(255, 255, 255, 0.3);
                width: 2rpx;
            }

            .btn-l {
                .tatol-price {
                    font-size: 32rpx;
                    font-weight: 600;
                    color: #ffffff;
                    line-height: 44rpx;
                }

                .discount {
                    font-size: 24rpx;
                    font-weight: 400;
                    color: #ffffff;
                }
            }

            .btn-r {
                display: flex;
                align-items: center;
                color: #fff;
                position: relative;

                .jt {
                    margin-left: 24rpx;
                    width: 18rpx;
                    height: 32rpx;
                }
            }
        }
    }
    .active-popup-box{
  position: relative;
  .close{
    position: absolute;
    right: 50%;
    transform: translateX(50%);
    bottom: -60rpx;
    width: 50rpx;
    height: 50rpx;
  }
}
.active-top-img{
  height: 320rpx;
  width: 100%;
  position: relative;
  top: 10rpx;
}
.active-popup-box{
  position: relative;
  .close{
    position: absolute;
    right: 50%;
    transform: translateX(50%);
    bottom: -60rpx;
    width: 50rpx;
    height: 50rpx;
  }
}
.active-top{
  position: relative;
  .title {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    white-space: nowrap;
    font-family: SourceHanSansCN, SourceHanSansCN;
    font-weight: 800;
    font-size: 60rpx;
    line-height: 90rpx;
    text-shadow: 0px 4px 8px rgba(175,57,27,0.25);
    text-align: center;
    font-style: normal;
    background-image: linear-gradient(270deg, #F8E2A7 0%, #FFFBE6 100%);
    background-clip: text;
    color: transparent;
  }
}
.active-popup {
  // padding: 20rpx;
  // border-radius: 20rpx;
  // background: #EA492B;
  height: 550rpx;
  display: flex;
  flex-direction: column;
  background-position: center center;
  background-repeat: no-repeat;
  // background-attachment: fixed;
  background-size: cover;
  position: relative;
  border-radius: 0 0 40rpx 40rpx;


  .list {
    flex: 1;
    overflow-y: scroll;
    padding: 0 24rpx;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 24rpx;
      height: 160rpx;
      padding: 0 24rpx;

      .item-l {
        text-align: center;
        margin-right: 20rpx;

        .time {
          font-size: 36rpx;
          font-weight: 600;
          color: #FF5D15;
          margin-bottom: 10rpx;
        }

        .time-m {
          background: rgba(255, 93, 21, 0.1);
          padding: 8rpx 12rpx;
          border-radius: 8rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: #FF5D15;
        }
      }

      .item-r {
        font-size: 30rpx;
        font-weight: 600;
        color: #333333;

        .name {
          margin-bottom: 20rpx;
        }

        .time {
          font-size: 26rpx;
          color: #999999;
          font-weight: 400;
        }
      }

      .icon {
        width: 36rpx;
        height: 36rpx;
      }
    }
  }

  .btn {
    height: 100rpx;
    background: linear-gradient(315deg, #00b952 0%, #00e565 100%);
    border-radius: 60rpx;
    line-height: 100rpx;
    text-align: center;
    font-size: 32rpx;
    font-weight: 600;
    color: #ffffff;
    margin-bottom: 20rpx;
  }
}
}
</style>